package com.camel.system.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.camel.core.controller.BaseCommonController;
import com.camel.core.entity.Result;
import com.camel.core.model.SysCompany;
import com.camel.core.model.SysUser;
import com.camel.core.service.BaseCommonService;
import com.camel.system.service.ISysCompanyService;
import com.camel.system.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author camel
 * @since 2022-11-29
 */
@RestController
@RequestMapping("/sysCompany")
public class SysCompanyController extends BaseCommonController<SysCompany> {

    @Autowired
    private SysUserService<SysUser> userService;

    @Override
    public boolean exist(SysCompany entity) {
        if(StringUtils.isEmpty(entity.getId())) {
            return service.count(new QueryWrapper<SysCompany>().eq("name", entity.getName())) > 0;
        }
        if(StringUtils.isEmpty(entity.getName())) {
            return false;
        }
        List<SysCompany> sysCompanyList = service.list(new QueryWrapper<SysCompany>().eq("name", entity.getName()));
         if(CollectionUtils.isEmpty(sysCompanyList)) {
             return false;
         }else if(sysCompanyList.size() > 1) {
            return true;
        } if(sysCompanyList.size() == 1) {
             return sysCompanyList.get(0).getId().equals(entity.getId());
        }
        return super.exist(entity);
    }

    @Override
    public Result update(@RequestBody SysCompany entity) {
        Result update = super.update(entity);
        if(update.isSuccess()) {
            List<SysUser> users = userService.list(new QueryWrapper<SysUser>().eq("company_id", entity.getId()));
            for (SysUser user : users) {
                user.setCompany(entity.getName());
            }
            userService.updateBatchById(users);
        }
        return update;
    }

    @Autowired
    private ISysCompanyService<SysCompany> service;

    @Override
    public BaseCommonService<SysCompany> getiService() {
        return service;
    }

    @Override
    public String getMouduleName() {
        return "公司";
    }
}
